import { Carousel, Empty, Skeleton } from 'antd';
import {
  CSSProperties, useEffect, useRef, useLayoutEffect
} from 'react';
import { CloseOutlined, RightOutlined } from '@ant-design/icons';
import { Drawer, useRefState, Button, udp } from '@cscec/udp-ui';
import styles from './index.less';
import { getEnableHomepage, getPCMenuList, getRecentUseMeneList, queryList, queryListBySortType, saveOrUpdateBatch, saveOrUpdatePersonModuleHomePage, updateFunctionSortType } from './service';
import { containerStyle } from '../common';
import { Content } from './components';
import { Card } from './components/Card';
import React from 'react';
import commonIcon from '@/assets/image/common.svg';
import commonArrowIcon from '@/assets/image/commonArrow.svg';

const moduleCode = udp.getQueryValue('moduleCode') || '1720259054527471617'

/**
 * 最常使用
 */
function InnerFc(props: {
  forceUpdate: object,
  setData: Function,
  setUpData: Function,
  setRecentUseData: Function,
  setManualData: Function,
  setClassData: Function,
  env: any,
  pageSize: number
}) {
  const [state, setState] = useRefState({
    loading: true,
    list: [] as any,
    updateList: [],
    recentUseList: [],
    manualList: [],
    classList: [],
    start: 0,
    pageSize:10
  });

  const carouselRef = useRef<any>();
  const myDivRef = useRef<any>();

  const getDataList = async () => {
    setState({ loading: true });
    const res = await getPCMenuList();
    if (res.code === 0) {
      let list: any = [];
      const classList: any = [];
      (res.data || []).map(e => {
        classList.push({
          label: e.moduleName,
          key: e.moduleCode,
          children: e.menuResponseList
        });
        list = [...list, ...e.menuResponseList];
      });

      props.setData(list || []);
      props.setClassData(classList || []);

      setState({
        loading: false,
        list,
        classList,
      });
    }
  };

  const queryDataList = async () => {
    setState({ loading: true });
    const res = await queryListBySortType();
    if (res.code === 0) {
      const result = (res.data || []).map(e => ({
        ...e,
        useFlg: 1,
      }));
      props.setUpData(result);
      setState({
        loading: false,
        updateList: result,
      });
    }
  };

  const getManualList = async () => {
    setState({ loading: true });
    const res = await queryList();
    if (res.code === 0) {
      props.setManualData(res.data || []);
      setState({
        loading: false,
        manualList: res.data,
      });
    }
  };

  const getRecentUseList = async () => {
    setState({ loading: true });
    const res = await getRecentUseMeneList();
    if (res.code === 0) {
      props.setRecentUseData(res.data || []);
      setState({
        loading: false,
        recentUseList: res.data,
      });
    }
  };  
 
  const calculatePageSize = () => {
    if (myDivRef.current) {
      const pageSize = Math.floor(((myDivRef.current.clientWidth+42) / 127)) * 2 || 2;
      setState({ pageSize });
    }
  };
  useLayoutEffect(() => {
    if (myDivRef.current) {
      calculatePageSize(); 
    }
  }, [myDivRef.current]);
  useEffect(()=>{
    const handleResize = () => {
      calculatePageSize();
    }; 
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  },[])

  useEffect(() => {
    queryDataList();
    getDataList();
    getRecentUseList();
    getManualList();
  }, [props.forceUpdate]);


  if (state.loading) {
    return (
      <div className={[styles.wrapper, styles.loading].join(' ')}>
        {new Array(5).fill(1).map((_, index) => (
          <div className={styles.item} key={index}>
            <Skeleton.Avatar className="hover-mask" active size={64} shape="square" style={{ marginLeft: 24 }} />
          </div>
        ))}
      </div>
    );
  }

  const len = state.updateList.length;
  if (!len) {
    return (
      <div style={{ paddingBottom: '30px' }}>
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      </div>
    )
  }

  const pageNum = Math.ceil(len / state.pageSize);
  const onChange = (currentSlide: number) => {
    setState({ start: currentSlide * state.pageSize });
  };

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
        {pageNum > 1 && <img
          src={commonArrowIcon}
          height={24}
          className={styles.leftArrow}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            carouselRef.current.prev();
          }}
        ></img>}
        <div className={styles.wrapper} ref={myDivRef} style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 230px))' }}>
          {state.updateList.slice(state.start, state.start + state.pageSize).map((item: any, index: any) => (
            <Card env={props.env} key={index} {...item} />
          ))}
        </div>
        {pageNum > 1 && <img
          src={commonArrowIcon}
          height={24}
          className={styles.rightArrow}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            carouselRef.current.next();
          }}
        ></img>}
      </div>
      <Carousel ref={carouselRef} afterChange={onChange}>
        {new Array(pageNum).fill(1).map((_, idx) => (
          <div key={idx}></div>
        ))}
      </Carousel>
    </div>
  );
}

export default function CommonFunction3(props: IProps) {
  const {
    commonTitle, style, env,
  } = props;
  const dataRef = useRef<{
    list: any[], updateList: any[], recentUseList: any[], classList: any[], manualList: any[]
  }>({
    list: [], updateList: [], recentUseList: [], classList: [], manualList: []
  });

  const [state, setState] = useRefState<any>({
    id: null,
    functionSortType: 0,
  });

  const showSetting = async () => {
    setState({
      showModal: true,
      modalTitle: '常用功能设置',
    });
  };

  const getHomepage = async () => {
    const rc = await getEnableHomepage();
    if (rc.code === 0) {
      const data = rc.data;

      if (data?.id) {
        setState({ id: data.id, functionSortType: data.functionSortType });
      } else if (data?.homepageId) {
        // 保存下个人模板
        const params = {
          homepageId: data.homepageId,
          homepageVersion: data.homepageVersion,
          moduleCode: data.moduleCode,
          personalHomepageName: data.personalHomepageName,
          personalHomepageContent: udp.CryptoJS.encode(data.personalHomepageContent),
        }
        const res = await saveOrUpdatePersonModuleHomePage(params);
        if (res.code === 0) {
          setState({ id: res.data, functionSortType: data.functionSortType });
        } else {
          udp.alert(res.message);
        }
      }
    } else {
      udp.alert(rc.message);
    }
  };

  useEffect(() => {
    getHomepage();
  }, []);

  const closeDrawer = () => {
    setState({ showModal: false });
  };

  const save = async () => {
    // 更新排序方式
    const sortType = udp.getCmpApi('sortType').getValue() === 'recent_use' ? 1 : 0;
    const rc = await updateFunctionSortType({
      id: state.id,
      functionSortType: sortType
    });
    rc.code !== 0 && udp.alert(rc.message);

    if (sortType === 0) {
      const params = {
        moduleCode,
        menuCodes: (dataRef.current.updateList || []).filter(e => e.useFlg === 1).map(e => e.menuCode)
      };
      const res = await saveOrUpdateBatch(params);
      if (res.code === 0) {
        setState({ showModal: false, functionSortType: sortType });
      } else {
        udp.alert(res.message);
      }
    } else {
      setState({ showModal: false, functionSortType: sortType });
    }
  };

  return (
    <div style={{ ...containerStyle, ...style, paddingTop: 0 }}>
      <div className={styles.topArea}>
        <div className={styles.topLeftArea}>
          <img src={commonIcon} height={18} style={{ verticalAlign: 'sub', marginRight: '8px' }}></img>
          常用功能
        </div>
        <div onClick={showSetting}>
          <span className={styles.topRight}>更多</span>
          <RightOutlined style={{ color: '#BABABB', cursor: 'pointer' }} />
        </div>
      </div>
      <InnerFc
        env={env}
        forceUpdate={{}}
        setData={(data: any[]) => { dataRef.current.list = data; }}
        setUpData={(data: any[]) => { dataRef.current.updateList = data; }}
        setRecentUseData={(data: any[]) => { dataRef.current.recentUseList = data; }}
        setClassData={(data: any[]) => { dataRef.current.classList = data; }}
        setManualData={(data: any[]) => { dataRef.current.manualList = data; }}
      />
      <Drawer
        title={'常用功能设置'}
        width='50vw'
        closable={false}
        onClose={closeDrawer}
        open={state.showModal}
        destroyOnClose
        zIndex={995}
        extra={<CloseOutlined onClick={closeDrawer} />}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button style={{ marginRight: 10 }} onClick={closeDrawer}>
              取消
            </Button>
            <Button type="primary" onClick={save}>
              确认
            </Button>
          </div>
        }
      >
        <Content dataRef={dataRef} functionSortType={state.functionSortType} />
      </Drawer>
    </div>
  );
}

export interface IProps {
  commonTitle: string;
  recentlyTitle: string;
  style?: CSSProperties;
  [x: string]: any;
}
